import axios from 'axios'
import router from '../router'
/* global  __APIHOST__ */
// 超时时间
axios.defaults.baseURL = __APIHOST__
axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.defaults.withCredentials = true
axios.defaults.transformRequest = function (request) {
  return JSON.stringify(request)
}

// http请求拦截器
axios.interceptors.request.use(function (config) {
  if (config.method === 'post') {
    config.data = {
      ...config.data,
      head: {
        token: sessionStorage.loginToken,
        channel: '',
        clientId: ''
      }
    }
  }
  return config
}, function (error) {
  return Promise.reject(error)
})

// http响应拦截器
axios.interceptors.response.use(function (res) {
  if (res.data.code === 4) {
    router.push(
      { path: '/user/login',
        query: { redirect: router.currentRoute.fullPath }
      })
  }
  if (res.data.head && res.data.head.token) {
    sessionStorage.setItem('loginToken', res.data.head.token)
  }

  return res
}, function (error) {
  return Promise.reject(error)
})

// 返回一个Promise(发送post请求)
export function fetchPost (url, params) {
  return new Promise((resolve, reject) => {
    axios.post(url, params)
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
      })
      .catch((error) => {
        reject(error)
      })
  })
}
// 返回一个Promise(发送get请求)
export function fetchGet (url, param) {
  return new Promise((resolve, reject) => {
    axios.get(url, { params: param })
      .then(response => {
        resolve(response.data)
      }, err => {
        reject(err)
      })
      .catch((error) => {
        reject(error)
      })
  })
}
export default axios
